let socket = null,
  lockReconnect = false, //是否真正建立连接
  timeout = 28 * 1000, //30秒一次心跳
  timeoutObj = null, //心跳心跳倒计时
  serverTimeoutObj = null, //心跳倒计时
  timeoutnum = null, //断开 重连倒计时
  leavePath = null, //判断是退出页面
  WebSocketData = "",
  socket_callback = null,
  valueIndex = "1";

function sendWebSocket(callback, index) {
  valueIndex = index;
  socket_callback = callback;
  initWebSocket(index);
}
// 初始化socket
function initWebSocket(index) {
  if (typeof WebSocket === "undefined") {
    alert("您的浏览器不支持socket");
  } else {
    socket = new WebSocket("ws://10.8.58.42:8880/websocket/" + index);
    // 监听socket连接
    socket.onopen = function () {
      WebSocketOnopen();
    };
    // 监听socket错误信息
    socket.onerror = function (e) {
      console.error("WebSocket连接出现错误:", e);  // 添加错误信息
      WebSocketOnerror(e);


    };
    // 监听socket消息
    socket.onmessage = function (e) {
      // WebSocketOnmessage(e);

      console.log("WebSocket message received:", e);  // 查看是否有消息收到
      try {
        WebSocketData = JSON.parse(e.data);
        console.log("Parsed WebSocket data:", WebSocketData);  // 打印解析后的数据
        socket_callback(WebSocketData);  // 调用回调处理数据
      } catch (error) {
        console.error("Failed to parse WebSocket message:", error);  // 捕捉解析错误
      }
      reset();
    };
    // 监听socket关闭
    socket.onclose = function (e) {
      WebSocketOnclose(e);
    };
  }
}


//重新连接WebSocket
function reconnect() {
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  timeoutnum && clearTimeout(timeoutnum);
  timeoutnum = setTimeout(() => {
    //新连接
    initWebSocket(valueIndex);
    lockReconnect = false;
  }, 5000);
}
//重置WebSocket心跳
function reset() {
  //清除时间
  clearTimeout(timeoutObj);
  clearTimeout(serverTimeoutObj);
  //重启心跳
  start();
}
//开启WebSocket心跳
function start() {
  timeoutObj && clearTimeout(timeoutObj);
  serverTimeoutObj && clearTimeout(serverTimeoutObj);
  timeoutObj = setTimeout(() => {
    //这里发送一个心跳，后端收到后，返回一个心跳消息，
    if (socket.readyState === 1) {
      //如果连接正常
      // socket.send("undefined");
      WebSocketOnsend(undefined);
    } else {
      //重连WebSocket
      reconnect();
    }
    serverTimeoutObj = setTimeout(() => {
      console.log("超时");
      //超时关闭
      socket.close();
    }, timeout);
  }, timeout);
}
// WebSocket连接成功
function WebSocketOnopen() {
  // var msg = JSON.stringify({cmd: 'enter_chatting', token:this.COOKIE.getCookie("token")});
  console.log("socket连接成功");
  //开启心跳
  start();
}
// WebSocket收到服务器返回信息
function WebSocketOnmessage(e) {
  console.log(e);
  if (e.data !== "undefined") {
    WebSocketData = JSON.parse(e.data);
    // console.log(WebSocketData)
    // console.log(WebSocketData.data)
    socket_callback(WebSocketData);
  }
  //收到服务器信息，心跳重置
  reset();
}
// WebSocket向服务器发送信息
function WebSocketOnsend(agentData) {
  // socket.send("主动发送信息");
  if (socket.readyState === socket.OPEN) {
    socket.send(JSON.stringify(agentData));
  }
}
// WebSocket关闭回调函数
function WebSocketOnclose(e) {
  // var msg = JSON.stringify({cmd: 'out_chatting', token:this.COOKIE.getCookie("token")});
  clearTimeout(timeoutObj);
  clearTimeout(serverTimeoutObj);
  clearTimeout(timeoutnum);
  // socket.close();
  console.log("离开页面WebSocket连接关闭");
}
// WebSocket错误回调函数
function WebSocketOnerror(e) {
  //重连WebSocket
  console.log("WebSocket连接出现错误");
  reconnect();
}

export { sendWebSocket, WebSocketOnclose };
